<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 角色管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.roleId" placeholder="角色编号" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-input v-model="query.roleNm" placeholder="角色名称" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="el-button" icon="el-icon-delete" @click="handleReset">重置</el-button>
                <div class="right-items" style="float: right;">
                    <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                </div>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column prop="roleId" label="角色编号" width="200" align="center"></el-table-column>
                <el-table-column prop="roleNm" label="角色名称" align="center"></el-table-column>
                <el-table-column prop="createUserAcct" label="创建者" align="center"></el-table-column>
                <el-table-column prop="roleRmk" label="角色说明" :show-overflow-tooltip="true" align="center"></el-table-column>
                <el-table-column prop="istTm" label="创建时间" align="center" sortable></el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-thumb"
                                @click="handleMenu(scope.$index, scope.row)"
                        >分配菜单</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%" :before-close="closeAdd">
            <el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="90px">
                <el-form-item label="角色编号:" prop="roleId">
                    <el-input v-model="addForm.roleId"></el-input>
                </el-form-item>
                <el-form-item label="角色名称:" prop="roleNm">
                    <el-input v-model="addForm.roleNm"></el-input>
                </el-form-item>
                <el-form-item label="角色说明:" prop="roleRmk">
                    <el-input v-model="addForm.roleRmk"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAdd">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%" :before-close="closeEdit">
            <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="90px">
                <el-form-item label="角色编号" prop="roleId">
                    <el-input disabled v-model="editForm.roleId" readonly></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleNm">
                    <el-input v-model="editForm.roleNm"></el-input>
                </el-form-item>
                <el-form-item label="角色说明" prop="roleRmk">
                    <el-input v-model="editForm.roleRmk"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配菜单弹出框 -->
        <el-dialog title="分配菜单" :visible.sync="menuVisible" width="30%">
            <el-tree
                    :data="menuTableData"
                    show-checkbox
                    node-key="menuId"
                    :default-expanded-keys="expandedKeys"
                    :default-checked-keys="checkedKeys"
                    ref="tree"
                    :props="defaultProps">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="menuVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getRoles,isNotExists,doAdd ,doUpdate,doDelete, selectByRoleId, doAddRoleMenu} from '../../../../api/system/role/role';
    import { menuData} from '../../../../api/system/menu/menu';
    export default {
        name: 'role',
        data() {
            return {
                query: {
                    roleId: '',
                    roleNm: '',
                    userAcct:localStorage.getItem('ms_userAcct'),
                    pageIndex: 1,
                    pageSize: 10
                },
                userAcct: localStorage.getItem('ms_userAcct'),
                tableData: [],
                multipleSelection: [],
                editVisible: false,
                addVisible:false,
                menuTableData:[],
                menuVisible:false,
                pageTotal: 0,
                editForm: {},
                addForm:{},
                idx: -1,
                id: -1,
                addFormRules: {
                    roleId: [
                        { required: true, message: '请输入角色编号', trigger: 'blur' },
                    ],
                    roleNm: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ]
                },
                editFormRules: {
                    roleId: [
                        { required: true, message: '请输入角色编号', trigger: 'blur' },
                    ],
                    roleNm: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ]
                },
                defaultProps: {
                    children: 'children',
                    label: 'menuTitle'
                },
                checkedKeys: [],
                expandedKeys: [],
                roleId: ""
            };
        },
        created() {
            this.getData();
        },
        methods: {
            // 获取后台数据
            getData() {
                getRoles(this.query).then(res => {
                    if (res.success === true){
                        this.tableData = res.data;
                        this.pageTotal = res.total;
                    } else {
                        this.$message.error("查询失败！");
                        this.tableData = [];
                        this.pageTotal = 0;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 触发重置按钮
            handleReset() {
                this.query.roleId = "";
                this.query.roleNm = "";
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    //后台进行删除操作
                    doDelete({roleId:row.roleId}).then(res => {
                        if (res.data==1){
                            this.$message.success('删除成功');
                            this.getData();
                        } else {
                            this.$message.error('删除失败');
                            this.getData();
                        }
                    });
                })
                    .catch(() => {
                        this.$message({
                            message:'已取消删除'
                        });
                    });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 新增操作
            handleAdd() {
                this.addForm={};
                this.addVisible = true;
            },
            /*新增角色*/
            saveAdd(){
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        //判断角色编号是否已存在
                        isNotExists({roleId:this.addForm.roleId}).then(isNotExistsres => {
                            if (isNotExistsres.data) {//编号不存在
                                //新增form表单提交到后台
                                this.addForm.createUserAcct = this.userAcct;
                                doAdd(this.addForm).then(res => {
                                    if (res.data == 1){
                                        this.addVisible=false;
                                        this.getData();
                                        this.$message.success('保存成功');
                                    }else{
                                        this.$message.error('保存失败');
                                    }
                                });
                            }else{//编号已存在
                                this.$message.error('该角色编号已存在');
                            }
                        });
                    }
                });
            },

            closeAdd(){//关闭新增弹出框
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.addVisible=false;
                        this.addForm={};
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message:'已取消操作'
                        });
                    });
            },
            // 编辑操作
            handleEdit(index, row) {
                this.editForm={};
                this.idx = index;
                this.editForm = row;
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                this.$refs['editForm'].validate((valid) => {
                    if (valid) {
                        doUpdate(this.editForm).then(res => {
                            if (res.data == 1) {
                                this.editVisible = false;
                                this.editForm = {};
                                this.getData();
                                this.$message.success('编辑成功');
                            } else {
                                this.$message.error('编辑失败');
                            }
                        });
                    }
                });
            },
            closeEdit(){//关闭编辑弹出框
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.editVisible=false;
                        this.editForm={};
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message:'已取消操作'
                        });
                    });
            },
            /*表单重置*/
            resetForm(refname){
                if (this.$refs[refname] !== undefined){
                    this.$refs[refname].resetFields();
                }
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            async handleMenu(index, row){
                this.roleId = row.roleId;
                this.checkedKeys = [];
                await menuData().then(res => {
                    if (res.success == true){
                        this.menuTableData = res.data;
                    } else {
                        this.menuVisible = true;
                        this.$message.error("查询失败！");
                        this.menuTableData = [];
                    }
                });
                await selectByRoleId({
                    roleId: row.roleId
                }).then(d => {
                    if (d.success == true){
                        let checkeds = [];
                        for (let i = 0; i < d.data.length; i++){
                            checkeds.push(d.data[i].menuId);
                        }
                        this.checkedKeys = checkeds;
                    }
                });
                this.menuVisible = true;
            },
            saveRoleMenu(){
                this.checkedKeys = this.$refs.tree.getCheckedKeys();
                doAddRoleMenu({
                    roleId: this.roleId,
                    menuId: this.checkedKeys.toString()
                }).then(res => {
                    if (res.success){
                        this.menuVisible = false;
                        this.getData();
                        this.$message.success('分配菜单成功');
                        this.menuTableData = [];
                        this.roleId = [];
                    } else {
                        this.$message.error("分配菜单失败！");
                    }
                });
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }

</style>
